package com.it.ymcc.interceptor;


import com.it.ymcc.annotation.PreAuthorize;
import com.it.ymcc.exception.BusinessException;
import com.it.ymcc.utils.JwtUtils;
import com.it.ymcc.utils.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(handler);

        String token = request.getHeader("Authorization");
        if (token != null) {
            //验证token
            Payload payload = JwtUtils.parseJwtToken(token);
            List<String> permissions = payload.getPermissions();
            if (handler instanceof HandlerMethod) {
                PreAuthorize methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(PreAuthorize.class);
                if (methodAnnotation == null) {
                    throw new BusinessException("无权限");
                }
                String sn = methodAnnotation.sn();
                if (!permissions.contains(sn)) {
                    throw new BusinessException("权限不足");
                }
            }
            // 将用户信息和权限信息存储到请求中，供后续拦截器使用
            return true;
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print("请先登录");
        return false;
    }
}
